<?php
abstract class DataMapper
{
    function getPDO()
    {
        global $_pdo;
        if (!isset($_pdo)) $_pdo = getPDO();
        return $_pdo;
    }

    function beginTransaction ()
    {
        $this->getPDO()->beginTransaction();
    }
    function commit ()
    {
        $this->getPDO()->commit();
    }
    function rollback ()
    {
        $this->getPDO()->rollback();
    }

    function getOrderString ($string)
    {
        $modelClass = static::MODEL_CLASS;
        $model = new $modelClass;
        
        $array = explode(',', $string);
        $return = '';
        
        foreach ($array as $v) {
            if (empty($v)) continue;
            
            $desc = false;
            if (substr($v,0,1) == '_') {
                $desc = true;
                $v = substr($v,1);
            }
            
            if ($model->isProperty($v)) {
                if (!empty($return))  $return .= ', ';
                $return .= $v;
                if ($desc) $return .= ' DESC';
            }
        }
        
        if (!empty($return)) $return = 'ORDER BY '.$return;
        return $return;
    }

    function getSearchString ($string, $searchMode, $column, $pdo, $return = '')
    {
        $array = explode(' ', $string);
        
        if (is_array($column)) {
            $ret = '';
            foreach ($column as $v) {
                if (!empty($ret)) $ret .= "||'\n'||";
                $ret .= "coalesce({$v},'')";
            }
            $column = $ret;
        }
        
        foreach ($array as $v) {
            if (empty($v)) continue;
            
            if (!empty($return))  $return .= ' AND ';
            $return .= $column . " {$searchMode} " . $pdo->quote('%'.$v.'%', PDO::PARAM_STR);
        }
        if (!empty($return)) $return = 'WHERE '.$return;
        return $return;
    }

    function getLimitString ($limit, $offset = null)
    {
        $return = null;
        if (!empty($limit)) {
            $return = 'LIMIT ' . $limit;
        }
        if (!empty($offset)) {
            $return .= ' OFFSET ' . (($offset-1) * $limit);
        }
        return $return;
    }


    protected function _decorate(PDOStatement $stmt, $query = null)
    {
        $stmt->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, static::MODEL_CLASS);
        //$stmt->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE);
        
        if ($query) {
            global $myGlobal;
            if (! isset($myGlobal['query']) ) $myGlobal['query'] = array();
            $myGlobal['query'][] = $query;
        }
        return $stmt;
    }
}